import React, {Component} from 'react'
import {fetchData} from '../../../components/AjaxConsumer'
import {
    Form,
    Input,
    Tooltip,
    Icon,
    Cascader,
    Select,
    Row,
    Col,
    Checkbox,
    Button,
    message,
    Modal,
    Radio,
    InputNumber,
    DatePicker
} from 'antd';
import styles from './index_ad.scss';
import { SelectUrl } from '../../../components';
import ListModelDetail from './SearchModel';
import moment from 'moment';
const FormItem = Form.Item;


const dateFormat = 'YYYY-MM-DD HH:mm:ss';

class UpdateForm extends React.Component {
    state = {
        loading: false,
        isEdit: false,
        submitUrl: '',
        waCodeUrl: '/base/data/area/get/wa_code',
        // unitLengthUrl:'/base/dic/get/unit_length',
        purchaseUrl:'/base/data/purchase/getPurchase',
        formData: {}
    };

    modelModalTableSearchClick = () => {
        this.refs.listModelDetail.showModal(this.state.formData.model);
    }

    popClick= () => {
        // const { form } = this.props;
        // const model = form.getFieldValue('model');
        // if(model == null){
            
        //     Modal.warning({
        //             title: '提示',
        //             content: '请选择型号！',
        //         });
        //     return;
        // }
        this.refs.listModelDetail.showModal(1);
        this.refs.listModelDetail.refreshHandle();
       // this.props.refreshHandle();
    };

    // 型号选择弹出模态框的统一回调函数
    getListModelDetailData = (resultData) => {
        // if(resultData.type=='instock'){
        // let model = 'model';
        // let productName = 'productName';
        // let density = 'density';
        // let spec = 'spec';
        // let requireAmount = 'requireAmount';
        // let grade = 'grade';
        // let level = 'level';
        this.props.form.setFieldsValue(
            {
                model: resultData.model,
                unit: resultData.unit,
                productName: resultData.productName,
                density: resultData.density,
                spec: resultData.spec,
                // grade: resultData.grade,
                // level: resultData.level
            }
        );
    }

    componentDidMount(){
        if(this.state.getData && this.state.getData != {}){
            console.log('-------componentDidMount----init----');
            let length = this.props.getData ? this.props.getData.data.length : 0;
            const data = this.state.getData.data;
            console.log(data)
            for(let i = 0; i < length; i++){
                if(i == 0){
                    // this.state.formData.contractNo = data[0].contractNo;
                    // this.state.formData.remark = data[0].remark;
                }

                let model = 'model';
                let productName = 'productName';
                let density = 'density';
                let spec = 'spec';
                let requireAmount = 'requireAmount';
                let grade = 'grade';
                let level = 'level';
                // let outPlanTime ='outPlanTime';
                this.props.form.setFieldsValue({[model]: data[i].model});
                this.props.form.setFieldsValue({[productName]: data[i].productName});
                this.props.form.setFieldsValue({[density]: data[i].density});
                this.props.form.setFieldsValue({[spec]: data[i].spec});
                this.props.form.setFieldsValue({[requireAmount]: data[i].requireAmount});
                this.props.form.setFieldsValue({[grade]: data[i].grade});
                this.props.form.setFieldsValue({[level]: data[i].level});
                // this.props.form.setFieldsValue({[outPlanTime]: data[i].outPlanTime});
            }
        }
    }

    handleSubmit = (e) => {
        e.preventDefault();
        this.props.form.validateFieldsAndScroll((err, fieldsValue) => {
            if (!err) {
                this.setState({loading: true});
                let values = {
                    ...fieldsValue,
                    // 'outPlanTime':outPlanTime? fieldsValue['outPlanTime'].format(dateFormat):null,
                };
                console.log('表单提交数据-----------', values);
                //发送ajax 控制请求数据规则，无值的设为空
                for (let item in values) {
                    if (!values[item]) {
                        values[item] = ''
                    }
                }
                const options = {
                    url: this.state.submitUrl,
                    type: 'post',
                    condition: values
                };

                fetchData(
                    this,
                    options,
                    (res) => {
                        //成功回调函数
                        this.setState({
                            loading: false
                        });
                        if (res.code == '1') {
                            message.success('操作成功');

                            this.handleCancel();
                            this.props.refreshHandle();
                        } else {
                            //message.error(res.msg);
                        }

                    },
                    (res) => {
                        this.setState({
                            loading: false
                        });
                    }
                )
            }
        });
    }

    handleCancel = () => {
        this.props.onCancel();//123
        this.props.form.resetFields(); //初始化表单
        //初始化ajax加载过来的selectList
    }

    //propertity 修改时执行
    componentWillReceiveProps(newProps){
        this.setState({
            isEdit: newProps.isEdit,
            submitUrl: newProps.submitUrl,
            formData: newProps.formData
        });
    }

    // 组件参数实例化-仅一次
    componentWillMount(){
        this.setState({
            isEdit: this.props.isEdit,
            submitUrl: this.props.submitUrl,
            formData: this.props.formData
        });
    }

    //保证 输入框只能填写数字
    handleKeyPress(event) {
        const invalidChars = ['-', '+', 'e', '.', 'E'];
        if(invalidChars.indexOf(event.key) !== -1){
            event.preventDefault();
        }
    }

    render() {
        const {getFieldDecorator} = this.props.form;
        const formItemLayout = {
            labelCol: {
                xs: {span: 24},
                sm: {span: 6}
            },
            wrapperCol: {
                xs: {span: 24},
                sm: {span: 18}
            }
        };
        const tailFormItemLayout = {
            wrapperCol: {
                xs: {span: 24, offset: 0},
                sm: {span: 24, offset: 10}
            }
        };

        let objectInfo = this.state.formData;
        return (
            <div>
                <Form
                    onSubmit={this.handleSubmit}
                    style={{
                                backgroundColor: '#fff',
                                paddingTop: '20px',
                                paddingBottom: '20px'
                            }}>
                    <Row>
                        <Col span={0}>
                            <FormItem>
                                {getFieldDecorator('sellOutId', {
                                    initialValue: objectInfo.sellOutId ? objectInfo.sellOutId.toString() : "",
                                    rules: [{}]
                                })(<Input type="hidden"/>)}
                            </FormItem>
                        </Col>
                        <Col span={23}>
                            <FormItem {...formItemLayout} label="型号">
                                {getFieldDecorator('model', {
                                    initialValue: this.state.formData.model ? this.state.formData.model : '',
                                    rules: [
                                        {
                                            required: true, whitespace: true, message: '请选择型号'
                                        }, {
                                            max: 100, message: '输入内容应少于100个字符'
                                        }
                                    ]
                                })(
                                //    <SelectUrl isDisable="true" url={this.state.contractUrl} type="get" dicCode="contractNo" dicName="contractNo" />
                                <Input type="remark" disabled rows={2} />
                                )}
                            </FormItem>
                        </Col>
                        <Col span={1} >
                            <Icon
                                className="dynamic-delete-button"
                                type="search"
                                onClick={() => this.popClick()}
                            />
                        </Col>
                        <Col span={0}>
                            <FormItem {...formItemLayout} label="品名">
                                {getFieldDecorator('productName', {
                                    initialValue: this.state.formData.productName ? this.state.formData.productName : '',
                                    rules: [{}]
                                })(<Input disabled />)}
                            </FormItem>
                        </Col>
                        <Col span={0}>
                            <FormItem {...formItemLayout} label="定量">
                                {getFieldDecorator('density', {
                                    initialValue: this.state.formData.density ? this.state.formData.density : '',
                                    rules: [{}]
                                })(<Input disabled />)}
                            </FormItem>
                        </Col>
                        <Col span={0}>
                            <FormItem {...formItemLayout} label="规格">
                                {getFieldDecorator('spec', {
                                    initialValue: this.state.formData.spec ? this.state.formData.spec : '',
                                    rules: [{}]
                                })(<Input disabled />)}
                            </FormItem>
                        </Col>
                        <Col span={23}>
                            <FormItem {...formItemLayout} label="仓库">
                                {getFieldDecorator('waCode', {
                                    initialValue: this.state.formData.waCode ? this.state.formData.waCode : '',
                                    rules: [
                                        {
                                            required: true,
                                            whitespace: true, 
                                            message: '请选择'
                                        }]
                                })(
                                    <SelectUrl url={this.state.waCodeUrl} type="get" dicCode="dicCode" dicName="dicName"/>
                                )}
                            </FormItem>
                        </Col>
                        <Col span={23}>
                            <FormItem {...formItemLayout} label="等级">
                                {getFieldDecorator('grade', {
                                    initialValue: this.state.formData.grade ? this.state.formData.grade : '',
                                    rules: [
                                        {
                                            required: true,
                                            whitespace: true, 
                                            message: '请选择'
                                        }]
                                })(
                                    <Select>
                                    <Select.Option value="1">一等品</Select.Option>
                                    <Select.Option value="2">二等品</Select.Option>
                                    <Select.Option value="3">处理品</Select.Option>
                                    </Select>
                                )}
                            </FormItem>
                        </Col>
                        <Col span={23}>
                            <FormItem {...formItemLayout} label="级别">
                                {getFieldDecorator('level', {
                                    initialValue: this.state.formData.level ? this.state.formData.level : '',
                                    rules: [
                                        {
                                            required: true,
                                            whitespace: true, 
                                            message: '请选择'
                                        }]
                                })(
                                    <Select>
                                    <Select.Option value="A">A</Select.Option>
                                    <Select.Option value="B">B</Select.Option>
                                    <Select.Option value="C">C</Select.Option>
                                    <Select.Option value="D">D</Select.Option>
                                    </Select>
                                )}
                            </FormItem>
                        </Col>
                        {/* <Col span={24}>
                            <FormItem {...formItemLayout} label="货主">
                                {getFieldDecorator('userDefined1', {
                                    initialValue: this.state.formData.userDefined1?this.state.formData.userDefined1:'',
                                    rules: [
                                        {
                                            required: true,whitespace: true,message: '请输入'
                                        },{
                                            max:100,message: '输入内容应少于100个字符'
                                        }
                                    ]
                                })(
                                    <SelectUrl url={this.state.purchaseUrl} type="get" dicCode="purchaseCode" dicName="purchaseName"/>
                                    // <Input type="textarea" rows={2} />
                                    // <Input type="text" />
                                )}
                            </FormItem>
                        </Col>
                        <Col span={24}>
                            <FormItem {...formItemLayout} label='箱号' hasFeedback>
                                {getFieldDecorator('userDefined3', {
                                    initialValue: this.state.formData.userDefined3?this.state.formData.userDefined3:'',
                                    rules: [{
                                        required: false, message: '请输入!'
                                    }, {
                                        whitespace: true, message: '不能为空'
                                    }]
                                })(<Input type="textarea" rows={2} />)}
                            </FormItem>
                        </Col>
                        <Col span={24}>
                            <FormItem {...formItemLayout} label="车牌">
                                {getFieldDecorator('userDefined2', {
                                    initialValue: this.state.formData.userDefined2?this.state.formData.userDefined2:'',
                                    rules: [
                                        {
                                            required: true,whitespace: true,message: '请输入'
                                        },{
                                            max:100,message: '输入内容应少于100个字符'
                                        }
                                    ]
                                })(
                                    <Input type="text" />
                                )}
                            </FormItem>
                        </Col> */}
                        <Col span={23}>
                            <FormItem {...formItemLayout} label="需求数量">
                                {getFieldDecorator('requireAmount', {
                                    initialValue: objectInfo.requireAmount ? objectInfo.requireAmount : 0,
                                    rules: [
                                        {
                                            required: true, message: '请输写数量'
                                        }
                                    ]
                                })(
                                    // <InputNumber min={0} max={9999} step={1} onChange={this.handleKeyPress}/>
                                    <Input placeholder="请填写" style={{ width:'254px'}} type='number' 
                                         min={1} step={1} onKeyPress={this.handleKeyPress} />
                                )}
                            </FormItem>
                        </Col>
                         <Col span={0}>
                            <FormItem {...formItemLayout} label="单位">
                                {getFieldDecorator('unit', {
                                    initialValue: objectInfo.unit ? objectInfo.unit : "",
                                    rules: [
                                        {
                                            required: true, whitespace: true, message: '请选择单位'
                                        }
                                    ]
                                })(<Input disabled />
                                    // <SelectUrl url={this.state.unitLengthUrl} type="get" dicCode="dicCode" dicName="dicName"/>
                                )}
                            </FormItem>
                        </Col>
                        {/* <Col span={24}>
                            <FormItem {...formItemLayout} label='生产日期'>
                                {getFieldDecorator('outPlanTime', {
                                    initialValue: this.state.formData.outPlanTime ?  moment(this.state.formData.outPlanTime,dateFormat):null,
                                    rules: [{ type: 'object', required: true, message: '日期不能为空'}]
                                })(
                                    // <DatePicker showTime format="YYYY-MM-DD HH:mm:ss" />
                                    <DatePicker format={'YYYY-MM-DD'} />
                                )}
                            </FormItem>
                        </Col> */}
                        <Col span={24} style={{ textAlign: 'center',marginTop:'10px' }}>
                                <Button type="primary" htmlType="submit" size="large">
                                    {this.state.loading ? '提交中...' : '确定'}
                                </Button>
                                <Button type="default" style={{marginLeft: '50px'}} size="large" onClick={this.handleCancel}>
                                    取消
                                </Button>
                        </Col>
                    </Row>
                </Form>

                <ListModelDetail getTableData={this.getListModelDetailData} ref='listModelDetail' />
            </div>
        );
    }
}

export default Form.create()(UpdateForm);

